subroutine rgp_fortran_der_hc_aaaa( &
       no, & ! (in)    number of occupied orbitals
       nv, & ! (in)    number of unoccupied orbitals
      Tia, & ! (in)    one electron integrals
    TVBjb, & ! (in)    contraction of T, V, and B
    TVBaj, & ! (in)    contraction of T, V, and B
      Bkl, & ! (in)    inverse matrix
      Ckl, & ! (in)    derivative contraciton with inverse matrix
      Via, & ! (in)    new rows
      Zia, & ! (in)    derivative contraction with new rows
     ZBia, & ! (out)   contraction of B and Z
     VCia, & ! (out)   contraction of C and V
   retval)   ! (inout) local derivative hamiltonian contraction

implicit none

integer,      intent(in)    ::     no
integer,      intent(in)    ::     nv
real(kind=8), intent(in)    ::    Tia(no,nv)
real(kind=8), intent(in)    ::  TVBjb(no,nv)
real(kind=8), intent(in)    ::  TVBaj(nv,no)
real(kind=8), intent(in)    ::    Bkl(no,no)
real(kind=8), intent(in)    ::    Ckl(no,no)
real(kind=8), intent(in)    ::    Via(no,nv) ! second index labels which row
real(kind=8), intent(in)    ::    Zia(no,nv) ! second index labels which row
real(kind=8), intent(out)   ::   ZBia(no,nv) ! second index labels which row
real(kind=8), intent(out)   ::   VCia(no,nv) ! second index labels which row
real(kind=8), intent(inout) :: retval

integer :: a, j

include 'formic/fqmc/rgp_fortran_interface.fpp'

! compute  ZBia
call rgp_fortran_build_vbia(no, nv, Bkl, Zia, ZBia)

! compute  VCia
call rgp_fortran_build_vbia(no, nv, Ckl, Via, VCia)

! one electron integral terms
retval = retval + ddot(no*nv, Tia, 1, ZBia, 1)
retval = retval + ddot(no*nv, Tia, 1, VCia, 1)

! two electron "diagonal" terms
retval = retval + 2.00d+00 * 0.50d+00 * ddot(no*nv, TVBjb, 1, ZBia, 1)
retval = retval + 2.00d+00 * 0.50d+00 * ddot(no*nv, TVBjb, 1, VCia, 1)

! two electron "off-diagonal" terms
do j = 1,no
do a = 1,nv
  retval = retval - 2.00d+00 * 0.50d+00 * TVBaj(a,j) * ZBia(j,a)
  retval = retval - 2.00d+00 * 0.50d+00 * TVBaj(a,j) * VCia(j,a)
enddo
enddo

end subroutine rgp_fortran_der_hc_aaaa
